package com.dm.cloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dm.cloud.api.dto.RoleResource;
import com.dm.cloud.api.service.IRoleResourceService;
import com.dm.cloud.common.R;
import com.dm.cloud.dao.RoleResourceDao;
import com.dm.cloud.utils.DtoPreOpratrionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RoleResourceServiceImpl implements IRoleResourceService {

   @Autowired
   private RoleResourceDao roleResourceDao;

    @Override
    public R createRoleResources(RoleResource roleResource) {
        if(null == roleResource.getRoleId()){
            return R.failure("10004_1","缺失角色信息");
        }
        if(null == roleResource.getResourceId()){
            return R.failure("10004_2","缺失资源信息");
        }
        //判断是否已经存在当前关系，存在则直接返回成功
        LambdaQueryWrapper<RoleResource> queryWrapper = new QueryWrapper<RoleResource>().lambda()
                .eq(RoleResource::getRoleId,roleResource.getRoleId())
                .eq(RoleResource::getResourceId,roleResource.getResourceId());
        if(roleResourceDao.selectCount(queryWrapper)>0){
            return R.success("角色资源绑定成功");
        }else{
            try{
                new DtoPreOpratrionUtils<RoleResource>().preInsert(roleResource);
                roleResourceDao.insert(roleResource);
                return R.success("角色资源绑定成功");
            }catch (Exception ex){
                return R.failure("10004_3","角色资源绑定失败！");
            }
        }
    }

    @Override
    public R deleteRoleResources(RoleResource roleResource) {

        //删除角色资源信息
        if(null != roleResource.getRoleId()){

            return R.failure("10005_4","缺失角色信息");
        }else if(null != roleResource.getResourceId() && null != roleResource.getRoleId()){

            return R.failure("10005_5","缺失角色信息");
        }else{

            return R.failure("10005_6","缺失角色资源信息");
        }
    }
}
